# 开奖页面后台


from django.db.models import Max
from django.shortcuts import render,redirect,HttpResponse
from web.models import open_shengxiao
from django import forms
def index(request):
    """
    首页：需要把以往的全部开奖记录都获取到
    """
    open_all = open_shengxiao.objects.all() # 获取全部的开奖数据
    
    content = {
        "open_all":open_all
    }
    
    return render(request,'后台/开奖/index.html',content)



"""
为什么同一个页面可以显示两种结果？
    - 前端是根据一个名为 is_show 来显示当前是新增还是编辑
    - 0 是新增
    - 1 是编辑



"""
        
# 新增赌期
def add_open(request):
    if request.method == 'GET':
        return render(request,'后台/开奖/add_edit.html',{
            "is_show":0
        })
    
    """
    
    <QueryDict: {'csrfmiddlewaretoken': ['gx9UgQFwVTwXdQzxQQkMafTobtnv5U6v89ZSSYvo10xIPknqPHQASoEaJ6eiTGcz'], 'open_time': ['2024-02-28'], 'open_shengxiao': ["['龙', '牛', '鸡', '羊', '蛇']"]}>
    
    """

    # 获取时间
    open_time = request.POST.get("open_time")

    # 获取开奖生肖
    new_open_shengxiao = request.POST.get("open_shengxiao")
    DQQS = int(open_shengxiao.objects.all().aggregate(Max('current_phase'))['current_phase__max']) + 1
    new_current_phase = DQQS
    open_shengxiao.objects.create(
        open_time=open_time,
        open_shengxiao=new_open_shengxiao,
        is_edit=False,
        current_phase=new_current_phase
    )

    return redirect('/data/open/index/')


# 编辑开奖结果

def edit_open(request,nid):
    """
    编辑开奖结果
    
    """
    if request.method == 'GET':
        # 根据nid获取本期的开奖结果
        row_object = open_shengxiao.objects.filter(current_phase=nid).first()
        
        return render(request,'后台/开奖/add_edit.html',{
            "data":row_object,
            "is_show":1
        })
    
    # 获取时间
    open_time = request.POST.get("open_time")

    # 获取开奖生肖
    new_open_shengxiao = request.POST.get("open_shengxiao")
    open_shengxiao.objects.filter().update(
        open_time=open_time,
        open_shengxiao=new_open_shengxiao,
        is_edit=False,
    )

    return redirect('/data/open/index/')



